import React, { Component } from 'react';
import { connect } from 'react-redux';
import Topic from './components/Topic';
import List from './components/List';
import Recommend from './components/Recommend';
import Writer from './components/Writer';
import {
    BackTop
} from './style';

import {
    HomeWrapper,
    HomeLeft,
    HomeRight

} from './style';
import { actionCreators } from './store';

class Home extends Component {

    componentDidMount() {
        this.props.initHome();
        this.bindEvents();
    }

    bindEvents() {
        window.addEventListener("scroll", this.props.changeScrollTopShow);
    }

    componentWillUnmount() {
        window.removeEventListener("scroll", this.props.changeScrollTopShow);
    }

    render() {
        return (
            <HomeWrapper>
                <HomeLeft>
                    <img alt="banner" className="banner-img" src="https://upload.jianshu.io/admin_banners/web_images/4677/a6d5d4ae2540976a7bd62e9db466b0301414d319.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540"/>
                    <Topic />
                    <List />
                </HomeLeft>
                <HomeRight>
                    <Recommend />
                    <Writer />
                </HomeRight>
                {
                    this.props.showScroll ? <BackTop onClick={this.handleScrollTop}>回到顶部</BackTop> : null
                }
            </HomeWrapper>
        );
    }

    handleScrollTop() {
        window.scrollTo(0, 0);
    }
}

const mapStateToProps = (state) => ({
    showScroll: state.getIn(["home", "showScroll"]),
});

const mapDispatchToProps = (dispatch) => {
    return {
        initHome: () => dispatch(actionCreators.initHome()),
        changeScrollTopShow: () => {
            const scrollTop = document.documentElement.scrollTop;
            if (scrollTop > 400) {
                dispatch(actionCreators.toggleTopShow());
            }  else {
                dispatch(actionCreators.toggleTopHide());
            }
        }
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);